// import { useRouter } from "vue-router";
import axios from "axios"
import router from '@/routes/index'
import { transParams } from './formatParams'
import { getToken, setToken } from "./auth";
const service = axios.create({
    baseURL: process.env.VUE_APP_BASE_API, 
    timeout: 1000 * 50
})

service.interceptors.request.use(
    (config: any) => {
        // 给请求头添加token
        config.headers['token'] = getToken()
        // get请求映射params参数
        if (config.method === 'get' && config.params) {
            let url = config.url + '?' + transParams(config.params);
            url = url.slice(0, -1);
            config.params = {};
            config.url = url;
        }
        return config
    },
    error => {
        Promise.reject(error)
    }
)

// response 拦截器,数据返回后进行一些处理
service.interceptors.response.use(
    (response: any) => {
        const res = response
        if (res.data.code == 200) {
            return res;
        } else if (res.data.code == 302) {
            Promise.reject(res.data.msg);
            setToken('')
            router.replace('/')
        } else {
            return Promise.reject(res);
        }
    },
    (err) => {
        return Promise.reject(err);
    }
)
export default service